<template>
  <div class="app-container">
    <!--对象搜索树型列表-->
    <el-form
      :model="queryParams"
      ref="queryRef"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="产品名称" prop="product">
        <y-select
          v-model="queryParams.product"
          placeholder="请选择产品名称"
          :optionsFunc="listProduct"
        />
      </el-form-item>
      <el-form-item label="任务名称" prop="job">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入任务名称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="执行状态" prop="status">
        <y-select
          v-model="queryParams.status"
          placeholder="请选择执行状态"
          :options="tms_job_status"
        />
      </el-form-item>
      <el-form-item label="创建时间" style="width: 308px">
        <el-date-picker
          v-model="dateRange"
          value-format="YYYY-MM-DD"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!--对象操作-->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Suitcase"
          @click="handleJobPlugins"
          >插件</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['tms:job:add']"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['tms:job:edit']"
          >修改</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="CaretRight"
          :disabled="single"
          @click="handleStart"
          v-hasPermi="['tms:job:start']"
          >执行</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="SwitchButton"
          :disabled="single"
          @click="handleStop"
          v-hasPermi="['tms:job:stop']"
          >停止</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['tms:job:delete']"
          >删除</el-button
        >
      </el-col>

      <y-right-toolbar
        v-model:showSearch="showSearch"
        @queryTable="getList"
        :columns="columns"
      />
    </el-row>

    <!--对象列表-->
    <el-table
      ref="tableRef"
      v-loading="loading"
      row-key="id"
      :data="jobList"
      @selection-change="handleSelectionChange"
      border
    >
      <el-table-column
        type="selection"
        width="55"
        align="center"
        reserve-selection
      />
      <el-table-column label="序号" width="100" align="center" type="index">
        <template #default="scope">
          {{ scope.$index + (queryParams.page - 1) * queryParams.limit + 1 }}
        </template>
      </el-table-column>
      <el-table-column
        label="任务编号"
        align="center"
        width="300"
        prop="id"
        v-if="columns[0].visible"
        sortable
        :show-overflow-tooltip="true"
      />
      <el-table-column
        label="任务名称"
        align="center"
        min-width="300"
        prop="name"
        :show-overflow-tooltip="true"
        v-if="columns[1].visible"
        sortable
      >
        <template #default="scope">
          <router-link
            :to="
              '/tms/job-info/index?job=' +
              scope.row.id +
              '&job_execution=' +
              scope.row.job_execution
            "
            class="link-type"
          >
            <span>{{ scope.row.name }}</span>
          </router-link>
        </template>
      </el-table-column>
      <el-table-column
        label="任务类型"
        width="110"
        align="center"
        prop="type"
        :show-overflow-tooltip="true"
        v-if="columns[2].visible"
        sortable
      >
        <template #default="scope">
          <y-dict-tag :options="tms_job_type" :value="scope.row.type" />
        </template>
      </el-table-column>
      <el-table-column
        label="执行状态"
        width="110"
        align="center"
        prop="status"
        v-if="columns[3].visible"
        sortable
      >
        <template #default="scope">
          <y-dict-tag :options="tms_job_status" :value="scope.row.status" />
        </template>
      </el-table-column>
      <el-table-column
        label="执行进度"
        width="250"
        align="center"
        v-if="columns[4].visible"
        sortable
      >
        <template #default="scope">
          <el-progress :percentage="scope.row.percentage" />
        </template>
      </el-table-column>
      <el-table-column
        label="创建时间"
        align="center"
        prop="create_time"
        width="180"
        v-if="columns[5].visible"
        sortable
      >
        <template #default="scope">
          <span>{{ parseTime(scope.row.create_time) }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="开始时间"
        align="center"
        prop="run_time"
        width="180"
        v-if="columns[6].visible"
        sortable
      >
        <template #default="scope">
          <span>{{ parseTime(scope.row.run_time) }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="结束时间"
        align="center"
        prop="finished"
        width="180"
        v-if="columns[7].visible"
        sortable
      >
        <template #default="scope">
          <span>{{ parseTime(scope.row.finished) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" fixed="right" align="center" width="260">
        <template #default="scope">
          <el-tooltip content="修改" placement="top">
            <el-button
              link
              type="primary"
              icon="Edit"
              @click="handleUpdate(scope.row)"
              v-hasPermi="['tms:job:edit']"
            >
            </el-button>
          </el-tooltip>
          <el-tooltip content="执行" placement="top">
            <el-button
              :disabled="scope.row.status == '1' || scope.row.status == '2'"
              link
              type="primary"
              icon="CaretRight"
              @click="handleStart(scope.row)"
              v-hasPermi="['tms:job:start']"
            >
            </el-button>
          </el-tooltip>
          <el-tooltip content="停止" placement="top">
            <el-button
              link
              type="primary"
              icon="SwitchButton"
              @click="handleStop(scope.row)"
              v-hasPermi="['tms:job:stop']"
            >
            </el-button>
          </el-tooltip>
          <el-tooltip
            v-if="scope.row.job_execution"
            content="统计"
            placement="top"
          >
            <el-button
              link
              type="primary"
              icon="PieChart"
              @click="handleStatistical(scope.row)"
              v-hasPermi="['tms:job:log']"
            >
            </el-button>
          </el-tooltip>
          <el-tooltip content="历史" placement="top">
            <el-button
              link
              type="primary"
              icon="ChatLineSquare"
              @click="handleHistory(scope.row)"
              v-hasPermi="['tms:job:log']"
            >
            </el-button>
          </el-tooltip>
          <el-tooltip
            v-if="scope.row.type === '1'"
            content="日志"
            placement="top"
          >
            <el-button
              link
              type="primary"
              icon="ChatDotSquare"
              @click="handleLog(scope.row)"
              v-hasPermi="['tms:job:log']"
            ></el-button>
          </el-tooltip>
          <el-tooltip content="删除" placement="top">
            <el-button
              link
              type="primary"
              icon="Delete"
              @click="handleDelete(scope.row)"
              v-hasPermi="['tms:job:delete']"
            ></el-button>
          </el-tooltip>
        </template>
      </el-table-column>
    </el-table>

    <!--列表分页-->
    <y-pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.page"
      v-model:limit="queryParams.limit"
      @pagination="getList"
    />

    <!-- 添加或修改对话框 -->
    <au-job
      :id="id"
      v-model="open"
      :title="title"
      :operate="operate"
      :getMethod="getJob"
      :addMethod="addJob"
      :updateMethod="updateJob"
      @submited="submited"
      @close="open = false"
    >
    </au-job>

    <!-- 添加或修改对话框 -->
    <statistic
      title="统计信息"
      :id="id"
      :level="level"
      v-model="openStatistic"
      @close="openStatistic = false"
    >
    </statistic>

    <!-- 用例日志详情展示 -->
    <el-dialog
      title="执行日志"
      v-model="openLog"
      width="1000px"
      @close="openLog = false"
      append-to-body
    >
      <el-form :model="form" label-width="100px">
        <el-input
          :rows="15"
          readonly="readonly"
          prop="detail"
          label-width="100px"
          v-model="form.detail"
          type="textarea"
        />
      </el-form>
    </el-dialog>
  </div>
</template>

<script setup name="JobManager">
import useUserStore from "@/store/modules/user";
import { listProduct } from "@/api/pms/product";
import {
  getJob,
  addJob,
  updateJob,
  startJob,
  stopJob,
  listJob,
  delJob,
} from "@/api/tms/job";
import AuJob from "./components/AuJob";
import Statistic from "./components/Statistic";

const router = useRouter();
const route = useRoute();
const { proxy } = getCurrentInstance();
const { tms_job_status, tms_job_type } = proxy.useDict(
  "tms_job_status",
  "tms_job_type"
);

const id = ref(null);
const ids = ref([]);
const idsn = ref([]);
const open = ref(false);
const openLog = ref(false);
const title = ref("");
const total = ref(0);
const level = ref("0");
const loading = ref(true);
const showSearch = ref(false);
const single = ref(true);
const multiple = ref(true);
const dateRange = ref([]);
const operate = ref("add");
const jobList = ref([]);
const openStatistic = ref(false);

// 列显隐信息
const columns = ref([
  { key: 0, label: `任务编号`, visible: false },
  { key: 1, label: `任务名称`, visible: true },
  { key: 2, label: `任务类型`, visible: true },
  { key: 3, label: `执行状态`, visible: true },
  { key: 4, label: `执行进度`, visible: true },
  { key: 5, label: `创建时间`, visible: true },
  { key: 6, label: `开始时间`, visible: true },
  { key: 7, label: `结束时间`, visible: true },
]);

const data = reactive({
  form: {},
  queryParams: {
    job: route.query.job,
    status: undefined,
    page: 1,
    limit: 10,
  },
});

const { queryParams, form } = toRefs(data);

/** 查询执行日志列表 */
function getList() {
  loading.value = true;
  listJob(proxy.addDateRange(queryParams.value, dateRange.value)).then(
    (response) => {
      jobList.value = response.data;
      total.value = response.total;
      loading.value = false;
    }
  );
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.page = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  dateRange.value = [];
  proxy.resetForm("queryRef");
  handleQuery();
}

/** 多选框选中数据 */
function handleSelectionChange(selection) {
  ids.value = selection.map((item) => item.id);
  idsn.value = selection.map((item) => item.name);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  operate.value = "add";
  open.value = true;
  title.value = "添加任务";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  id.value = row.id || ids.value;
  operate.value = "update";
  open.value = true;
  title.value = "修改任务";
}

/** 任务插件列表查询 */
function handleJobPlugins() {
  router.push({
    path: "/tms/job-plugin/index",
  });
}

/** 开始执行*/
function handleStart(row) {
  ids.value = row.id ? [row.id] : ids.value;
  idsn.value = row.name || idsn.value;
  proxy.$modal
    .confirm('确认要开始执行"' + idsn.value + '"任务吗?')
    .then(function () {
      useUserStore()
        .getInfo()
        .then((res) => {
          // row.executor = res.data.user.id;
          // updateJob(row).then((res) => {

          // });
          startJob(ids.value).then(() => {
            getList();
            proxy.$modal.msgSuccess("任务开始执行");
          });
        });
    });
}

/** 停止执行*/
function handleStop(row) {
  ids.value = row.id ? [row.id] : ids.value;
  idsn.value = row.name || idsn.value;
  proxy.$modal
    .confirm('确认要停止执行"' + idsn.value + '"任务吗?')
    .then(function () {
      stopJob(ids.value).then((res) => {
        getList();
        proxy.$modal.msgSuccess(res.msg);
      });
    });
}

/** 删除按钮操作 */
async function handleDelete(row) {
  try {
    if (row.id) {
      await proxy.$modal.confirm(`确认是否删除 "${row.name}" ？`);
    } else {
      await proxy.$modal.confirm("确认是否删除所有已勾选信息？");
    }
    ids.value = row.id ? [row.id] : ids.value;
    await delJob(ids.value);
    proxy.$modal.msgSuccess("删除成功");
    proxy.$refs.tableRef.clearSelection();
    getList();
  } catch (error) {
    console.error(error);
  }
}

/** 统计信息按钮操作 */
function handleStatistical(row) {
  id.value = row.job_execution;
  openStatistic.value = true;
  level.value = row.level;
}

/** 任务日志列表查询 */
function handleHistory(row) {
  if (row.id) {
    router.push({
      path: "/tms/job-execution/index",
      query: { job: row.id },
    });
  }
}

/** 详细日志按钮操作 */
function handleLog(row) {
  openLog.value = true;
  form.value = row;
}

/** 添加/修改对象后触发事件 */
function submited() {
  getList();
}

onMounted(() => {
  getList();
});
</script>
